package logic

import (
	"context"
	"errors"
	"math/rand"
	"time"
	"video-hubs/model/cache"
	"video-hubs/videorpc/internal/svc"
	"video-hubs/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *videorpc.SendSmsRequest) (*videorpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	s, _ := cache.Rdb.Get(cache.Ctx, "send"+in.Username).Result()
	if s != "" {
		return nil, errors.New("一分钟只能发送一次")
	}
	code := rand.Intn(9000) + 1000
	//sms, err := pkg.SendSms(in.Username, strconv.Itoa(code))
	//if err != nil {
	//	return nil, err
	//}
	//if sms.Code != 2 {
	//	return nil, err
	//}
	cache.Rdb.Set(cache.Ctx, "sendSms"+in.Username, code, time.Minute*5)
	result, _ := cache.Rdb.Incr(cache.Ctx, "number"+in.Username).Result()
	if result == 1 {
		cache.Rdb.Expire(cache.Ctx, "sendSms"+in.Username, time.Minute*5)
	}
	cache.Rdb.Set(cache.Ctx, "send"+in.Username, 1, time.Minute*1)

	return &videorpc.SendSmsResponse{}, nil
}
